<?php

namespace app\controller\open;

use app\BaseController;
use app\model\Supplier;
use think\facade\Cache;
use think\helper\Str;
use think\Response;

class Auth extends BaseController
{
    public function token(): Response
    {
        $param = $this->request->param();
        //获取商家
        $supplier = $this->app->make(Supplier::class)->where('appid', $param['appid'])->where('state', 1)->find();
        if (empty($supplier)) throw new \Exception('渠道账号不存在！',7044);
        //校验渠道签名
        $sign = md5($param['appid'] . $param['timestamp'] . $supplier['token']);
        if (strtoupper($sign) != strtoupper($param['sign'])) throw new \Exception('签名错误！',4097);
        //判断渠道是否有未过期的token
        if (Cache::has("{$param['appid']}_token")) {
            return $this->success(Cache::get("{$param['appid']}_token"));
        }
        return $this->extracted($param['appid']);
    }

    public function refresh(): Response
    {
        $param = $this->request->param();
        if (!Cache::has("{$param['appid']}_refresh_token")) throw new \Exception('refresh_token不存在！',7045);
        if (Cache::get("{$param['appid']}_refresh_token") != $param['refresh_token']) throw new \Exception('refresh_token不存在！',7045);
        //获取商家
        $supplier = $this->app->make(Supplier::class)->where('appid', $param['appid'])->where('state', 1)->find();
        if (empty($supplier)) throw new \Exception('渠道账号不存在！',7044);
        //校验渠道签名
        $sign = md5($param['appid'] . $param['refresh_token'] . $param['timestamp'] . $supplier['token']);
        if (strtoupper($sign) != strtoupper($param['sign'])) throw new \Exception('签名错误！',4097);
        return $this->extracted($param['appid']);
    }

    /**
     * @param $appid
     * @return Response
     */
    public function extracted($appid): Response
    {
        $data = [
            "expires_time" => strtotime("+2 hour"), //过期时间戳
            "access_token" => Str::random(32, 9), //请求token
            "refresh_token" => Str::random(32, 9), // 刷新token
            "timer" => 7200
        ];
        Cache::set("{$appid}_token", $data, 7200);
        Cache::set("{$appid}_refresh_token", $data['refresh_token'], 8000);
        return $this->success($data);
    }
}
